package xyz.zinglizingli.books.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import xyz.zinglizingli.books.RestTemplateUtil;
import xyz.zinglizingli.books.mapper.BookContentMapper;
import xyz.zinglizingli.books.mapper.BookIndexMapper;
import xyz.zinglizingli.books.mapper.BookMapper;
import xyz.zinglizingli.books.po.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@Service
public class BookService {

    @Autowired
    private BookMapper bookMapper;

    @Autowired
    private BookIndexMapper bookIndexMapper;

    @Autowired
    private BookContentMapper bookContentMapper;

    RestTemplate restTemplate = RestTemplateUtil.getInstance("utf-8");


    private Logger log = LoggerFactory.getLogger(BookService.class);


    @Transactional
    public void saveBookAndIndexAndContent(Book book, List<BookIndex> bookIndex, List<BookContent> bookContent) {
        boolean isUpdate = false;
        Long bookId = -1l;
        book.setBookName(book.getBookName().trim());
        book.setAuthor(book.getAuthor().trim());
        BookExample example = new BookExample();
        example.createCriteria().andBookNameEqualTo(book.getBookName()).andAuthorEqualTo(book.getAuthor());
        List<Book> books = bookMapper.selectByExample(example);
        if (books.size() > 0) {
            //更新
            bookId = books.get(0).getId();
            book.setId(bookId);
            bookMapper.updateByPrimaryKeySelective(book);
            isUpdate = true;

        } else {
            if (book.getVisitCount() == null) {
                Long visitCount = generateVisiteCount(book.getScore());
                book.setVisitCount(visitCount);
            }
            //插入
            int rows = bookMapper.insertSelective(book);
            if (rows > 0) {
                bookId = book.getId();
            }


        }

        if (bookId >= 0) {
            //查询目录已存在数量
           /* BookIndexExample bookIndexExample = new BookIndexExample();
            bookIndexExample.createCriteria().andBookIdEqualTo(bookId);
            int indexCount = bookIndexMapper.countByExample(bookIndexExample);*/


            List<BookIndex> newBookIndexList = new ArrayList<>();
            List<BookContent> newContentList = new ArrayList<>();
            for (int i = 0; i < bookIndex.size(); i++) {
                BookContent bookContentItem = bookContent.get(i);
                if (!bookContentItem.getContent().contains("正在手打中，请稍等片刻，内容更新后，需要重新刷新页面，才能获取最新更新")) {


                    BookIndex bookIndexItem = bookIndex.get(i);
                    bookIndexItem.setBookId(bookId);
                    bookContentItem.setBookId(bookId);
                    //bookContentItem.setIndexId(bookIndexItem.getId());暂时使用bookId和IndexNum查询content
                    bookContentItem.setIndexNum(bookIndexItem.getIndexNum());

                    newBookIndexList.add(bookIndexItem);
                    newContentList.add(bookContentItem);
                }
            }

            if (newBookIndexList.size() > 0) {
                bookIndexMapper.insertBatch(newBookIndexList);

                bookContentMapper.insertBatch(newContentList);
            }


            if (isUpdate) {
                //sendNewstIndex(newBookIndexList);
            } else {
                //sendNewstBook(bookId);
            }


        }


    }

    private Long generateVisiteCount(Float score) {
        int baseNum = (int) (Math.pow(score * 10, (int) (score - 5)) / 2);
        return Long.parseLong(baseNum + new Random().nextInt(1000) + "");
    }


    public int queryMaxIndexNum(Long bookId) {
        BookIndexExample example = new BookIndexExample();
        example.createCriteria().andBookIdEqualTo(bookId);
        return bookIndexMapper.countByExample(example) - 1;
    }

    public boolean isExsitBook(String bookName, String author) {


        BookExample example = new BookExample();
        example.createCriteria().andBookNameEqualTo(bookName.trim()).andAuthorEqualTo(author.trim());
        return bookMapper.countByExample(example) > 0 ? true : false;

    }


    /**
     * 查询该书籍目录数量
     */
    public List<Integer> queryIndexCountByBookNameAndBAuthor(String bookName, String author) {
        List<Integer> result = new ArrayList<>();
        BookExample example = new BookExample();
        example.createCriteria().andBookNameEqualTo(bookName).andAuthorEqualTo(author);
        List<Book> books = bookMapper.selectByExample(example);
        if (books.size() > 0) {

            Long bookId = books.get(0).getId();
            BookIndexExample bookIndexExample = new BookIndexExample();
            bookIndexExample.createCriteria().andBookIdEqualTo(bookId);
            List<BookIndex> bookIndices = bookIndexMapper.selectByExample(bookIndexExample);
            if (bookIndices != null && bookIndices.size() > 0) {
                for (BookIndex bookIndex : bookIndices) {
                    result.add(bookIndex.getIndexNum());
                }
            }

        }

        return result;

    }


    private void sendNewstBook(Long bookId) {
        //http://data.zz.baidu.com/urls?appid=1643715155923937&token=fkEcTlId6Cf21Sz3&type=batch

        //List<String> idList = queryEndBookIdList();
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.TEXT_PLAIN);
        //headers.add("User-Agent","curl/7.12.1");
        headers.add("Host", "data.zz.baidu.com");

        String reqBody = "";
        reqBody += ("https://www.zinglizingli.xyz/book/" + bookId + ".html" + "\n");
        //reqBody += ("http://www.zinglizingli.xyz/book/" + bookId + ".html" + "\n");
        headers.setContentLength(reqBody.length());
        HttpEntity<String> request = new HttpEntity<>(reqBody, headers);
        System.out.println("推送数据：" + reqBody);
        ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity("http://data.zz.baidu.com/urls?site=www.zinglizingli.xyz&token=IuK7oVrPKe3U606x", request, String.class);
        System.out.println("推送URL结果：code:" + stringResponseEntity.getStatusCode().value() + ",body:" + stringResponseEntity.getBody());
        try {
            Thread.sleep(1000);

            //reqBody += ("http://www.zinglizingli.xyz/book/" + bookId + ".html" + "\n");
            System.out.println("推送数据：" + reqBody);
            stringResponseEntity = restTemplate.postForEntity("http://data.zz.baidu.com/urls?appid=1643715155923937&token=fkEcTlId6Cf21Sz3&type=batch", request, String.class);
            System.out.println("推送URL结果：code:" + stringResponseEntity.getStatusCode().value() + ",body:" + stringResponseEntity.getBody());
        } catch (InterruptedException e) {
            log.error(e.getMessage(), e);
        }

    }


    private void sendNewstIndex(List<BookIndex> bookIndex) {

        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.TEXT_PLAIN);
        //headers.add("User-Agent","curl/7.12.1");
        headers.add("Host", "data.zz.baidu.com");

        String reqBody = "";
        if (bookIndex.size() > 0) {
            BookIndex index = bookIndex.get(bookIndex.size() - 1);//目录只推送最新一条
            reqBody += ("https://www.zinglizingli.xyz/book/" + index.getBookId() + "/" + index.getIndexNum() + ".html" + "\n");
            //reqBody += ("http://www.zinglizingli.xyz/book/" + index.getBookId() + "/" + index.getIndexNum() + ".html" + "\n");
            headers.setContentLength(reqBody.length());
            HttpEntity<String> request = new HttpEntity<>(reqBody, headers);
            System.out.println("推送数据：" + reqBody);
            ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity("http://data.zz.baidu.com/urls?site=www.zinglizingli.xyz&token=IuK7oVrPKe3U606x", request, String.class);
            System.out.println("推送URL结果：code:" + stringResponseEntity.getStatusCode().value() + ",body:" + stringResponseEntity.getBody());

            try {
                Thread.sleep(1000);
                //reqBody += ("http://www.zinglizingli.xyz/book/" + index.getBookId() + "/" + index.getIndexNum() + ".html" + "\n");
                System.out.println("推送数据：" + reqBody);
                stringResponseEntity = restTemplate.postForEntity("http://data.zz.baidu.com/urls?appid=1643715155923937&token=fkEcTlId6Cf21Sz3&type=batch", request, String.class);
                System.out.println("推送URL结果：code:" + stringResponseEntity.getStatusCode().value() + ",body:" + stringResponseEntity.getBody());

            } catch (InterruptedException e) {
                log.error(e.getMessage(), e);
            }


        }


    }

    public List<String> queryNoEndBookIdList() {

        return bookMapper.queryNoEndBookIdList();
    }
}
